import { JKManager } from "../JKManager";

const NativeCallback = {
    ShowTips: 0,
    HideWait: 1,
}

//#region 谷歌数据埋点配置
export type GoogleAnalyticsEvent =
    `Launch` |
    `Level_Start` |
    `enterRemoveAd` |
    `buyRemoveAdSuccess` |
    `choosePiece16` |
    `choosePiece36` |
    `choosePiece64` |
    `choosePiece100` |
    `choosePiece144` |
    `choosePiece256` |
    `choosePiece400` |
    `choosePiece625` |
    `choosePiece900` |
    `openRotate` |
    `closeRotate` |
    `useTool0` |
    `useTool1` |
    `useTool2` |
    `useTool3` |
    `finish16` |
    `finish36` |
    `finish64` |
    `finish100` |
    `finish144` |
    `finish256` |
    `finish400` |
    `finish625` |
    `finish900` |
    `enterChoosePieceFromNext` |
    `startGameFromNext` |
    `enterGameView` |
    `enterFinishView` |
    `Enter_Dailyquests` |
    `Finished_Dailyquests1` |
    `Finished_Dailyquests2` |
    `Finished_Dailyquests3` |
    `Enter_BuyPuzzle` |
    `Finished_BuyPuzzle` |
    `Enter_BuyPuzzle_Banner` |
    `Finished_BuyPuzzle_Banner` |
    `Look_CarCulture_Banner` |
    `Look_ColorfulButterfly_Banner` |
    `Look_FamousPaintings_Banner` |
    `Look_MysteryMask_Banner` |
    `Look_LandmarkBuilding_Banner` |
    `Look_MicroscopicInsects_Banner` |
    `Look_ColorfulMushrooms_Banner` |
    `Look_SunnyBeach_Banner` |
    `Look_ChineseArchitecture_Banner` |
    `Look_UnderwaterWorld_Banner` |
    `Look_Italy_Banner` |
    `Look_DIno_Banner` |
    `Look_Universe_Banner` |
    `Enter_BuyAtlas_CarCulture_Banner` |
    `Enter_BuyAtlas_ColorfulButterfly_Banner` |
    `Enter_BuyAtlas_FamousPaintings_Banner` |
    `Enter_BuyAtlas_MysteryMask_Banner` |
    `Enter_BuyAtlas_LandmarkBuilding_Banner` |
    `Enter_BuyAtlas_MicroscopicInsects_Banner` |
    `Enter_BuyAtlas_ColorfulMushrooms_Banner` |
    `Enter_BuyAtlas_SunnyBeach_Banner` |
    `Enter_BuyAtlas_ChineseArchitecture_Banner` |
    `Enter_BuyAtlas_UnderwaterWorld_Banner` |
    `Enter_BuyAtlas_Italy_Banner` |
    `Enter_BuyAtlas_Dino_Banner` |
    `Enter_BuyAtlas_Universe_Banner` |
    `Finished_BuyAtlas_CarCulture_Banner` |
    `Finished_BuyAtlas_ColorfulButterfly_Banner` |
    `Finished_BuyAtlas_FamousPaintings_Banner` |
    `Finished_BuyAtlas_MysteryMask_Banner` |
    `Finished_BuyAtlas_LandmarkBuilding_Banner` |
    `Finished_BuyAtlas_MicroscopicInsects_Banner` |
    `Finished_BuyAtlas_ColorfulMushrooms_Banner` |
    `Finished_BuyAtlas_SunnyBeach_Banner` |
    `Finished_BuyAtlas_ChineseArchitecture_Banner` |
    `Finished_BuyAtlas_UnderwaterWorld_Banner` |
    `Finished_BuyAtlas_Italy_Banner` |
    `Finished_BuyAtlas_Dino_Banner` |
    `Finished_BuyAtlas_Universe_Banner` |
    `FirstDay_Play_1min` |
    `FirstDay_Play_2mins` |
    `FirstDay_Play_4mins` |
    `FirstDay_Play_6mins` |
    `FirstDay_Play_8mins` |
    `FirstDay_Play_10mins` |
    `FirstDay_Play_12mins` |
    `FirstDay_Play_14mins` |
    `FirstDay_Play_16mins` |
    `FirstDay_Play_18mins` |
    `FirstDay_Play_20mins` |
    `FirstDay_Play_22mins` |
    `FirstDay_Play_24mins` |
    `FirstDay_Play_26mins` |
    `FirstDay_Play_28mins` |
    `FirstDay_Play_30mins` |
    `Enter_Categories_View` |
    `Enter_Categories_Allpuzzles` |
    `Enter_Categories_Collections` |
    `Finished_BuyAtlas_Collections` |
    `Enter_BuyAtlas_CarCulture` |
    `Finished_BuyAtlas_CarCulture` |
    `Enter_BuyAtlas_FamousPaintings` |
    `Finished_BuyAtlas_FamousPaintings` |
    `Enter_BuyAtlas_ColorfulButterfly` |
    `Finished_BuyAtlas_ColorfulButterfly` |
    `Enter_BuyAtlas_MysteryMask` |
    `Finished_BuyAtlas_MysteryMask` |
    `Enter_BuyAtlas_LandmarkBuilding` |
    `Finished_BuyAtlas_LandmarkBuilding` |
    `Enter_BuyAtlas_MicroscopicInsects` |
    `Finished_BuyAtlas_MicroscopicInsects` |
    `Enter_BuyAtlas_ColorfulMushrooms` |
    `Finished_BuyAtlas_ColorfulMushrooms` |
    `Enter_BuyAtlas_SunnyBeach` |
    `Finished_BuyAtlas_SunnyBeach` |
    `Enter_BuyAtlas_ChineseArchitecture` |
    `Finished_BuyAtlas_ChineseArchitecture` |
    `Enter_BuyAtlas_UnderwaterWorld` |
    `Finished_BuyAtlas_UnderwaterWorld` |
    `Enter_BuyAtlas_Italy` |
    `Finished_BuyAtlas_Italy` |
    `Enter_BuyAtlas_Dino` |
    `Finished_BuyAtlas_Dino` |
    `Enter_BuyAtlas_Universe` |
    `Finished_BuyAtlas_Universe` |
    `Enter_Categories_Mysterypuzzles` |
    `Enter_Picture_Mysterypuzzles` |
    `Enter_Categories_Pets` |
    `Enter_Picture_Pets` |
    `Enter_Categories_Landmarks` |
    `Enter_Picture_Landmarks` |
    `Enter_Categories_Nature` |
    `Enter_Picture_Nature` |
    `Enter_Categories_Art` |
    `Enter_Picture_Art` |
    `Enter_Categories_Transport` |
    `Enter_Picture_Transport` |
    `Enter_Categories_Brids` |
    `Enter_Picture_Brids` |
    `Enter_Categories_objects` |
    `Enter_Picture_objects` |
    `Enter_Categories_Food` |
    `Enter_Picture_Food` |
    `Enter_Categories_Colors` |
    `Enter_Picture_Colors` |
    `Enter_Categories_Home` |
    `Enter_Picture_Home` |
    `Enter_Categories_Flowers` |
    `Enter_Picture_Flowers` |
    `Enter_Categories_Animals` |
    `Enter_Picture_Animals` |
    `Enter_Dailypuzzles_View` |
    `Enter_Dailypuzzles_Banner` |
    `Enter_Picture_Dailypuzzles` |
    `Click_Create_Puzzle` |
    `Succeed_Create_Puzzle` |
    `Finished_Any_CarCulture` |
    `Finished_Any_FamousPaintings` |
    `Finished_Any_ColorfulButterfly` |
    `Finished_Any_MysteryMask` |
    `Finished_Any_LandmarkBuilding` |
    `Finished_Any_MicroscopicInsects` |
    `Finished_Any_ColorfulMushrooms` |
    `Finished_Any_SunnyBeach` |
    `Finished_Any_ChineseArchitecture` |
    `Finished_Any_UnderwaterWorld` |
    `Finished_Any_Italy` |
    `Finished_Any_Dino` |
    `Finished_Any_Universe`
//#endregion

/**
 * 商品配置
 */
export type GoogelProduct = {
    responseCode?: GooglePlayBuyResultCode,
    productId: GoogleProductId,
    productType?: GoogleProductType,
}
//#region 商品id
export type GoogleProductId =
    //订阅商品id
    `ptyx2_month_vip_9.99` |
    `ptyx2_week_vip_4.99` |
    `ptyx2_year_vip_69.99` |
    //移除广告id 
    `ptyx2_remove_ads_3.99` |
    `ptyx2_puzzle_0.99` |
    `ptyx2_collection_3.99` |
    `NONE`
//#endregion
//#region 商品类型
export type GoogleProductType =
    `inapp` | // 一次性商品
    `subs`// 订阅商品
//#endregion
/**
 * 商品详情
 */
export type ProductDetails = {
    productId: GoogleProductId,
    productType: GoogleProductType,
    name: string,
    title: string,
    description: string,
    oneTimePurchaseOfferDetails: OfferDetail[],
    subscriptionOfferDetails: OfferDetail[],
}
type ProductDetailsData = {
    productId: GoogleProductId,
    productType: GoogleProductType,
    name: string,
    title: string,
    description: string,
    oneTimePurchaseOfferDetails: string,
    subscriptionOfferDetails: string,
}
/**
 * 商品购买可用方案详情
 */
export type OfferDetail = {
    offerTags: string[],
    offerToken: string, // 令牌
    pricingPhases: {
        billingCycleCount: number,
        billingPeriod: string,
        formattedPrice: string,
        priceAmountMicros: number,
        priceCurrencyCode: string,
        recurrenceMode: string,
    }[]
}
//#region 商品购买结果
export type GooglePlayBuyResultCode =
    -1 | // 查询有效订阅和非消耗型一次性购买交易回调
    0 | //成功
    1 | //用户按上一步或取消对话框
    2 | //网络连接断开
    3 | //所请求的类型不支持 Google Play 结算服务 AIDL 版本
    4 | //请求的商品已不再出售
    5 | //提供给 API 的参数无效。此错误也可能说明应用未针对 Google Play 结算服务正确签名或设置，或者在其清单中缺少必要的权限。
    6 | //API 操作期间出现严重错误
    7 | //未能购买，因为已经拥有此商品
    8 //未能消费，因为尚未拥有此商品
//#endregion
/**
 * 订单详情
 */
export type GooglePurchase = {
    kind: string,
    purchaseTimeMillis: string,
    purchaseState: number,
    consumptionState: number,
    developerPayload: string,
    orderId: string,
    purchaseType: number,
    acknowledgementState: number,
    purchaseToken: string,
    productId: string,
    quantity: number,
    obfuscatedExternalAccountId: string,
    obfuscatedExternalProfileId: string,
    regionCode: string
}

//#region 广告结果
export type AdResult =
    `Finished` |
    `UnFinished` |
    `NotReady`
//#endregion

/**
 * 云控插屏广告配置
 */
let FirebaseRemoteConfig = {
    /**
     * is_safe_level	新手插屏保护X局	2局
     */
    is_safe_level: null,
    /**
     * is_safe_time	新手插屏保护X时间	300s
     */
    is_safe_time: null,
    /**
     * is_time	插屏cd	120s
     */
    is_time: null,
    /**
     * is_hint_prop	每天只能观看x次视频获得1魔法棒道具	10
     */
    is_hint_prop: null
}
export type FirebaseRemoteConfig = typeof FirebaseRemoteConfig
export type FirebaseRemoteKey = keyof FirebaseRemoteConfig
export type InnerAdData = {
    [firebaseRemoteKey in FirebaseRemoteKey]: number
}

/**
 * 第三方平台功能管理
 */
export class SocialManager {
    /**
     * 评价地址
     */
    readonly EvaluateUrl = `https://play.google.com/store/apps/details?id=com.puzzlegames.jigsaw.puzzles.free`
    /**
     * 技术支持网址
     */
    readonly SupportUrl = `http://www.firephoenixgame.com/`
    /**
     * 隐私协议
     */
    readonly PrivacyPolicyUrl = `http://www.firephoenixgame.com/privacy`
    /**
     * 用户协议
     */
    readonly TermsOfServicesUrl = `http://www.firephoenixgame.com/terms`

    /**
     * Google Play Billing
     */
    private _googlePlayBuyCall: (googlePlayBuyResult: GooglePlayBuyResultCode, productId: GoogleProductId) => void;
    private _googlePlayQueryPurchasesAsync: (productId: GoogleProductId) => void;
    /**
     * 云控插屏广告配置
     */
    private _innerAdData: InnerAdData
    get innerAdData() {
        return this._innerAdData
    }
    set innerAdData(innerAdData) {
        this._innerAdData = innerAdData
    }

    init() {
        cc.log(`${cc.js.getClassName(this)} init`);

        this.initGooglePlayBilling()
        this.initAd()
        this.getFireBaseRemoteConfig((data) => {
            this.innerAdData = data as InnerAdData
        })
    }

    //==============================================================================================================================
    //========================================================= 内部方法 ============================================================
    //==============================================================================================================================

    //==============================================================================================================================
    //========================================================= 外部方法 ============================================================
    //==============================================================================================================================

    /**
     * 发送分享邮件
     */
    sendEmail() {
        cc.log(`${cc.js.getClassName(this)} sendEmail`)

        if (!CC_PREVIEW) {
            if (cc.sys.isNative && !cc.sys.isBrowser) {
                let title = `Jigsaw Puzzles`,
                    content = ``
                if (cc.sys.os === cc.sys.OS_ANDROID) {
                    jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `sendEmail`, `(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V`, JKManager.AppConfig.ShareEmail, content, '2444554624445546')
                } else if (cc.sys.os === cc.sys.OS_IOS) {
                    let data = [
                        title,
                        content,
                        JKManager.AppConfig.IOSAppUrl,
                    ]
                    jsb.reflection.callStaticMethod(`SocialManager`, `sendEmail:`, JSON.stringify(data))
                }
            }
        }
    }

    /**
     * 分享app
     */
    shareApp() {
        cc.log(`${cc.js.getClassName(this)} shareApp`)

        if (!CC_PREVIEW) {
            if (cc.sys.isNative && !cc.sys.isBrowser) {
                let title = `Jigsaw Puzzles`,
                    content = JKManager.Language.getText(`shareapptips`),
                    shareMsgObj = [
                        title,
                        content,
                    ]
                if (cc.sys.os === cc.sys.OS_ANDROID) {
                    shareMsgObj.push(JKManager.AppConfig.AndroidAppUrl)
                    jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `shareApp`, `(Ljava/lang/String;)V`, JSON.stringify(shareMsgObj))
                } else if (cc.sys.os === cc.sys.OS_IOS) {
                    shareMsgObj.push(JKManager.AppConfig.IOSAppUrl)
                    jsb.reflection.callStaticMethod(`SocialManager`, `shareAppWithShareMsg:`, JSON.stringify(shareMsgObj))
                }
            }
        }
    }

    /**
     * 分享本地或远程图片到第三方应用
     * @param resUrl 资源地址
     * @param costTime 完成时间
     * @param step 完成步数
     */
    shareRes(resUrl: string, costTime: string = ``, step: string = ``) {
        cc.log(`${cc.js.getClassName(this)} shareRes resUrl = ${resUrl}`)

        if (!CC_PREVIEW) {
            if (cc.sys.isNative && !cc.sys.isBrowser) {
                let shareMsg = `${JKManager.Language.getText(`slogan2`)} ${JKManager.AppConfig.AndroidAppUrl}`
                if (!costTime || !step) {
                    shareMsg = `${JKManager.Language.getText(`slogan2`)} ${JKManager.AppConfig.AndroidAppUrl}`
                } else {
                    shareMsg = shareMsg.replace('$param1', `${costTime}`);
                    shareMsg = shareMsg.replace('$param2', `${step}`);
                }

                if (cc.sys.os == cc.sys.OS_ANDROID) {
                    jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `shareRes`, `(Ljava/lang/String;Ljava/lang/String;)V`, resUrl, shareMsg)
                } else if (cc.sys.os == cc.sys.OS_IOS) {
                    jsb.reflection.callStaticMethod(`SocialManager`, `shareResWithResUrl:shareMsg:`, resUrl, shareMsg)
                }
            }
        }
    }

    /**
     * 保存图片到本地并加入相册
     * @param imgUrl 图片地址
     */
    saveImg(imgUrl: string) {
        cc.log(`${cc.js.getClassName(this)} saveImg imgUrl = ${imgUrl}`)

        if (!CC_PREVIEW) {
            if (cc.sys.isNative && !cc.sys.isBrowser) {
                if (cc.sys.os == cc.sys.OS_ANDROID) {
                    jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `saveImg`, `(Ljava/lang/String;)V`, imgUrl);
                } else if (cc.sys.os == cc.sys.OS_IOS) {
                    jsb.reflection.callStaticMethod(`SocialManager`, `saveImgWithImgUrl:`, imgUrl);
                }
            }
        }
    }

    //========================================================= FireBase Analytics ============================================================

    /**
     * Google Analytics 打点数据上报
     * @param eventId 事件id
     * @param data 数据对象
     */
    reportEvent(eventId: GoogleAnalyticsEvent, data: object = {}) {
        cc.log(`${cc.js.getClassName(this)} reportEvent eventId = ${eventId}`)

        if (!CC_PREVIEW) {
            if (cc.sys.isNative && !cc.sys.isBrowser) {
                if (cc.sys.os === cc.sys.OS_ANDROID) {
                    jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `reportEvent`, `(Ljava/lang/String;Ljava/lang/String;)V`, eventId, JSON.stringify(data))
                } else if (cc.sys.os === cc.sys.OS_IOS) {
                    jsb.reflection.callStaticMethod(`SocialManager`, `reportEvent:eventId:content:`, `false`, eventId, JSON.stringify(data))
                }
            }
        }
    }

    //========================================================= FireBase Remote Config ============================================================

    /**
     * 获取 FireBase 云控配置数据
     * @param call 数据回调
     */
    getFireBaseRemoteConfig(call: (remoteData: FirebaseRemoteConfig) => void) {
        cc.log(`${cc.js.getClassName(this)} getFireBaseRemoteConfig`)

        if (!CC_PREVIEW) {
            if (cc.sys.isNative && !cc.sys.isBrowser) {
                let firebaseRemotekeys = Object.keys(FirebaseRemoteConfig);
                (window as any).JKManager.onGetFireBaseRemoteConfig = (datas: string[]) => {
                    cc.log(`${cc.js.getClassName(this)} onGetFireBaseRemoteConfig datas = ${datas}`)

                    let remoteData = cc.js.createMap() as FirebaseRemoteConfig
                    datas.forEach((data: string, index: number) => {
                        remoteData[firebaseRemotekeys[index]] = data
                    })
                    call && call(remoteData)
                }

                if (cc.sys.os === cc.sys.OS_ANDROID) {
                    jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `getFireBaseRemoteConfig`, `(Ljava/lang/String;)V`, JSON.stringify(firebaseRemotekeys))
                } else if (cc.sys.os === cc.sys.OS_IOS) {
                    jsb.reflection.callStaticMethod(`SocialManager`, `getFireBaseRemoteConfigWithKeys:`, JSON.stringify(firebaseRemotekeys))
                }
            }
        }
    }

    //========================================================= Google Play Billing ============================================================

    /**
     * 初始化 Google Play Billing
     */
    initGooglePlayBilling() {
        cc.log(`${cc.js.getClassName(this)} initGooglePlayBilling`);

        (window as any).JKManager.onGetProduct = (googlePlayProduct: GoogelProduct) => {
            cc.log(`${cc.js.getClassName(this)} onGetProduct googlePlayProduct = `, googlePlayProduct)

            let responseCode = googlePlayProduct.responseCode,
                productId = googlePlayProduct.productId
            if (responseCode < 0) {
                if (this._googlePlayQueryPurchasesAsync) {
                    this._googlePlayQueryPurchasesAsync(productId)
                }
            } else {
                if (this._googlePlayBuyCall) {
                    this._googlePlayBuyCall(responseCode, productId)
                }
            }
        }

        if (!CC_PREVIEW) {
            if (cc.sys.isNative && !cc.sys.isBrowser) {
                if (cc.sys.os === cc.sys.OS_ANDROID) {
                    jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `initGooglePlayBilling`, `()V`)
                } else if (cc.sys.os === cc.sys.OS_IOS) {
                    jsb.reflection.callStaticMethod(`SocialManager`, `initGooglePlayBilling`, `false`)
                }
            }
        }
    }

    /**
     * 批量查询指定商品详情
     * @param products 商品信息
     */
    queryProductDetailsAsync(products: GoogelProduct[], call: (productDetailsList: ProductDetails[]) => void) {
        cc.log(`${cc.js.getClassName(this)} queryProductDetailsAsync products = `, products)

        if (!CC_PREVIEW) {
            if (cc.sys.isNative && !cc.sys.isBrowser) {
                (window as any).JKManager.onGetProductDetailsAsync = (productDetailsList: ProductDetailsData[]) => {
                    cc.log(`${cc.js.getClassName(this)} onGetProductDetailsAsync productDetailsList = `, productDetailsList)

                    call && call(productDetailsList.map((productDetailsData: ProductDetailsData) => {
                        let productDetails: ProductDetails = cc.js.createMap()
                        productDetails.oneTimePurchaseOfferDetails = JKManager.Utils.parseJSON(productDetailsData.oneTimePurchaseOfferDetails) as OfferDetail[]
                        productDetails.subscriptionOfferDetails = JKManager.Utils.parseJSON(productDetailsData.subscriptionOfferDetails) as OfferDetail[]
                        cc.js.addon(productDetails, productDetailsData)

                        return productDetails
                    }))
                }

                let array = products.map(product => JSON.stringify(product))
                if (cc.sys.os === cc.sys.OS_ANDROID) {
                    jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `queryProductDetailsAsync`, `(Ljava/lang/String;)V`, JSON.stringify(array))
                } else if (cc.sys.os === cc.sys.OS_IOS) {
                    jsb.reflection.callStaticMethod(`SocialManager`, `queryProductDetailsAsyncWithProductIds:`, `false`, JSON.stringify(array))
                }
            }
        }
    }

    /**
     * 购买指定商品
     * @param productId 商品id
     * @param productType 类型
     * @param call 结果回调
     */
    googlePlayBuy(productId: GoogleProductId, productType: GoogleProductType, call: (googlePlayBuyResult: GooglePlayBuyResultCode, productId: GoogleProductId) => void) {
        cc.log(`${cc.js.getClassName(this)} googlePlayBuy productId = ${productId} productType = ${productType}`)

        if (!CC_PREVIEW) {
            if (cc.sys.isNative && !cc.sys.isBrowser) {
                this._googlePlayBuyCall = call
                if (cc.sys.os === cc.sys.OS_ANDROID) {
                    jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `googlePlayBuy`, `(Ljava/lang/String;Ljava/lang/String;)V`, productId, productType)
                } else if (cc.sys.os === cc.sys.OS_IOS) {
                    jsb.reflection.callStaticMethod(`SocialManager`, `googlePlayBuyWithProductId:productType:`, `false`, productId, productType)
                }
            }
        }
    }

    /**
     * 查询有效订阅和非消耗型一次性购买交易
     * @param call 结果回调
     */
    googlePlayQueryPurchasesAsync(call: (productId: GoogleProductId) => void) {
        cc.log(`${cc.js.getClassName(this)} googlePlayQueryPurchasesAsync`)

        if (!CC_PREVIEW) {
            if (cc.sys.isNative && !cc.sys.isBrowser) {
                this._googlePlayQueryPurchasesAsync = call
                if (cc.sys.os === cc.sys.OS_ANDROID) {
                    jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `googlePlayQueryPurchasesAsync`, `()V`)
                } else if (cc.sys.os === cc.sys.OS_IOS) {
                    jsb.reflection.callStaticMethod(`SocialManager`, `googlePlayQueryPurchasesAsync`, `false`)
                }
            }
        }
    }

    /**
     * 查询用户针对每个商品发起的最近一笔购买记录，即使该购买交易已过期、已取消或已消耗，也仍会提取相关记录
     */
    googlePlayQueryPurchaseHistoryAsync(call: (googlePurchase: GooglePurchase) => void) {
        cc.log(`${cc.js.getClassName(this)} googlePlayQueryPurchaseHistoryAsync`)

        if (!CC_PREVIEW) {
            if (cc.sys.isNative && !cc.sys.isBrowser) {
                (window as any).JKManager.onGetPurchaseHistoryAsync = (googlePurchase: GooglePurchase) => {
                    let a = {
                        "zza": "{\"productId\":\"ptyx2_remove_ads_3.99\",\"purchaseTime\":1655841233830,\"purchaseToken\":\"fajbgaamhpbpakhicoifkjii.AO-J1OzL1Hhh8Gy9bGNq-IMtlbfuCgPk1hmXfhxb89D8r4ccGDuhLaqXk9lStrQGO2azCBZgYWzNN2Omj6YAMmgjwatJnkpmw2EB5XWBq_a1MXeq1yf1ibc\",\"quantity\":1}", "zzb": "V3wRIQZawYGzlLo/gsDLEkCrUUiD5g0H/qHSTXjTwWI0DikujLpZ8AA7y22Kexfuqke4XVhRgeyd0qpEIi10RUu+DqsC4cCyedCI8KVvCdbfqfLmy25/ocpmal4OKmJjbywYa5oUErLCUv4FsPJWO4lQ2tFFfnQVftd8ucb9s0N4HfSyedklW0tkxOkQ1klBduAzTJZhaRta2GORIHaGmAovr1epwUtfB+F3IIWYOA6qkl0UotQ16AH73NAtfT1sU06sFaVpvyYhDytWBcB/dze4Ji8jYqtDkHutA0BT7TollYzy3Mv0nS1CK0K8mtIxIo9rwdqxBCgsR9bsisJQnA\u003d\u003d", "zzc": { "nameValuePairs": { "productId": "ptyx2_remove_ads_3.99", "purchaseTime": 1655841233830, "purchaseToken": "fajbgaamhpbpakhicoifkjii.AO-J1OzL1Hhh8Gy9bGNq-IMtlbfuCgPk1hmXfhxb89D8r4ccGDuhLaqXk9lStrQGO2azCBZgYWzNN2Omj6YAMmgjwatJnkpmw2EB5XWBq_a1MXeq1yf1ibc", "quantity": 1 } }
                    }
                    call && call(googlePurchase)
                }
                if (cc.sys.os === cc.sys.OS_ANDROID) {
                    jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `googlePlayQueryPurchaseHistoryAsync`, `()V`)
                } else if (cc.sys.os === cc.sys.OS_IOS) {
                    jsb.reflection.callStaticMethod(`SocialManager`, `googlePlayQueryPurchaseHistoryAsync`, `false`)
                }
            }
        }
    }

    //========================================================= 广告 ============================================================

    /**
     * 初始化广告
     */
    initAd() {
        cc.log(`${cc.js.getClassName(this)} initAd`)

        if (!CC_PREVIEW) {
            if (cc.sys.isNative && !cc.sys.isBrowser) {
                if (cc.sys.os === cc.sys.OS_ANDROID) {
                    jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `initAd`, `()V`)
                } else if (cc.sys.os === cc.sys.OS_IOS) {
                    jsb.reflection.callStaticMethod(`SocialManager`, `initAd`, `false`)
                }
            }
        }
    }

    /**
     * 显示横幅广告
     * @param call 回调
     */
    showBanner(call: (isFullWatch: AdResult) => void = null) {
        cc.log(`${cc.js.getClassName(this)} showBanner JKManager.AppConfig.AdEnabled = ${JKManager.AppConfig.AdEnabled} JKManager.AppConfig.AdBannerEbabled = ${JKManager.AppConfig.AdBannerEbabled}`)

        if (!CC_PREVIEW) {
            if (JKManager.AppConfig.AdEnabled && JKManager.AppConfig.AdBannerEbabled) {
                if (cc.sys.isNative && !cc.sys.isBrowser) {
                    (window as any).JKManager.onBannerAdFinished = (isFullWatch: AdResult) => {
                        cc.log(`${cc.js.getClassName(this)} showBanner onBannerAdFinished isFullWatch = ${isFullWatch}`)

                        call && call(isFullWatch)
                    }
                    if (cc.sys.os === cc.sys.OS_ANDROID) {
                        jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `showBanner`, `()V`)
                    } else if (cc.sys.os === cc.sys.OS_IOS) {
                        jsb.reflection.callStaticMethod(`SocialManager`, `showBanner`, `false`)
                    }
                }
            } else {
                call && call(`Finished`)
            }
        }
    }

    /**
     * 隐藏横幅广告
     */
    hideBanner(): void {
        cc.log(`${cc.js.getClassName(this)} hideBanner`)

        if (!CC_PREVIEW) {
            if (cc.sys.isNative && !cc.sys.isBrowser) {
                if (cc.sys.os === cc.sys.OS_ANDROID) {
                    jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `hideBanner`, `()V`)
                } else if (cc.sys.os === cc.sys.OS_IOS) {
                    jsb.reflection.callStaticMethod(`SocialManager`, `hideBanner`, `false`)
                }
            }
        }
    }

    /**
     * 检测是否需要播放插屏广告
     */
    checkInnerVideo(): boolean {
        cc.log(`${cc.js.getClassName(this)} checkInnerVideo`)

        if (this.innerAdData || CC_PREVIEW) {
            let innerVideoCDTime = JKManager.LocalStorage.getData<number>(JKManager.LocalStorage.LocalStorageKey.InnerVideoCDTime),
                innerSafeLevel = JKManager.LocalStorage.getData<number>(JKManager.LocalStorage.LocalStorageKey.InnerSaveLevel),
                innerSafeTime = JKManager.LocalStorage.getData<number>(JKManager.LocalStorage.LocalStorageKey.InnerSafeTime)

            if (innerVideoCDTime == null) {
                innerVideoCDTime = 0
            }
            if (innerSafeLevel == null) {
                innerSafeLevel = 0
                JKManager.LocalStorage.setData(JKManager.LocalStorage.LocalStorageKey.InnerSaveLevel, innerSafeLevel)
            }
            if (innerSafeTime == null) {
                innerSafeTime = Date.now()
                JKManager.LocalStorage.setData(JKManager.LocalStorage.LocalStorageKey.InnerSafeTime, innerSafeTime)
            }
            let saveLevel = this.innerAdData ? this.innerAdData.is_safe_level : 2
            let safeTime = this.innerAdData ? this.innerAdData.is_safe_time : 300
            let cdTime = this.innerAdData ? this.innerAdData.is_time : 120

            let now = Date.now()
            let condition1 = innerSafeLevel > saveLevel // 插屏广告新手保护局数
            let condition2 = now - innerSafeTime > safeTime * 1000 // 插屏广告保护时间
            let condition3 = now - innerVideoCDTime > cdTime * 1000 // 插屏广告冷却时间

            return condition1 && condition2 && condition3
        }

        return false
    }

    /**
     * 刷新拼图局数，以检测插屏广告新手保护局数
     */
    addInnerSafeLevelCnt() {
        cc.log(`${cc.js.getClassName(this)} addInnerSafeLevelCnt`)

        if (JKManager.SocialManager.innerAdData || CC_PREVIEW) {
            let innerSafeLevel = JKManager.LocalStorage.getData<number>(JKManager.LocalStorage.LocalStorageKey.InnerSaveLevel),
                saveLevel = JKManager.SocialManager.innerAdData ? JKManager.SocialManager.innerAdData.is_safe_level : 2
            if (innerSafeLevel <= saveLevel) {
                innerSafeLevel += 1
                JKManager.LocalStorage.setData(JKManager.LocalStorage.LocalStorageKey.InnerSaveLevel, innerSafeLevel)
            }
        }
    }

    /**
     * 显示插屏广告
     * @param call 回调
     */
    showInter(call: (isFullWatch: AdResult) => void): void {
        cc.log(`${cc.js.getClassName(this)} showInter JKManager.AppConfig.AdEnabled = ${JKManager.AppConfig.AdEnabled}`)

        if (!CC_PREVIEW) {
            if (JKManager.AppConfig.AdEnabled) {
                if (cc.sys.isNative && !cc.sys.isBrowser) {
                    (window as any).JKManager.onInterAdFinished = (adResult: AdResult) => {
                        cc.log(`${cc.js.getClassName(this)} showInter onInterAdFinished adResult = ${adResult}`)

                        call && call(adResult)
                    }
                    if (cc.sys.os === cc.sys.OS_ANDROID) {
                        jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `showInter`, `()V`)
                    } else if (cc.sys.os === cc.sys.OS_IOS) {
                        jsb.reflection.callStaticMethod(`SocialManager`, `showInter`, `false`)
                    }
                }
            } else {
                call && call(`Finished`)
            }
        } else {
            call && call('Finished')
        }
    }

    /**
     * 显示激励广告
     * @param call 回调
     */
    showVideo(call: (adResult?: AdResult) => void) {
        cc.log(`${cc.js.getClassName(this)} showInter JKManager.AppConfig.AdEnabled = ${JKManager.AppConfig.AdEnabled}`)

        if (!CC_PREVIEW) {
            if (JKManager.AppConfig.AdEnabled) {
                if (cc.sys.isNative && !cc.sys.isBrowser) {
                    (window as any).JKManager.onVideoAdFinished = (adResult: AdResult) => {
                        cc.log(`${cc.js.getClassName(this)} showVideo onVideoAdFinished adResult = ${adResult}`)

                        call && call(adResult)
                    }
                    if (cc.sys.os === cc.sys.OS_ANDROID) {
                        jsb.reflection.callStaticMethod(`jkCore/social/SocialManager`, `showVideo`, `()V`)
                    } else if (cc.sys.os === cc.sys.OS_IOS) {
                        jsb.reflection.callStaticMethod(`SocialManager`, `showVideo`, `false`)
                    }
                }
            } else {
                call && call(`Finished`)
            }
        } else {
            call && call('Finished');
        }
    }
}